package com.feijie.thread_demo.SyncContrast;

/**
 * @program: thread_demo
 * @description: 对比synchonized的静态方法和代码块锁的对象
 * @author: 作者
 * @create: 2022-03-07 11:54
 */
public class sync {

    /**
     * 其中代码块中锁对象与静态方法中锁对象不一样。
     */

    static class TestSyn {
        public void A() {
            synchronized (this){
                /**
                 * 此时this对象锁为  实例  对象锁
                 */
                System.out.println(this.getClass().getName().toString());

                try {
                    System.out.println("before A " + Thread.currentThread().getName());
                    Thread.sleep(10000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("after A " + Thread.currentThread().getName());
            }
        }

        public synchronized static void B() {
            /**
             * 此时静态方法中的对象锁为  class 对象锁
             */
            try {
                System.out.println("before B " + Thread.currentThread().getName());
                Thread.sleep(10000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("after B " + Thread.currentThread().getName());
        }

    }

    public static void main(String[] args) {
        TestSyn testSyn = new TestSyn();
        Thread t1 = new Thread(testSyn::A);
        Thread t2 = new Thread(TestSyn::B);
        t1.start();
        t2.start();
    }

}
